package com.mstore.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.mstore.config.Constants;
import com.mstore.interceptor.Authority;
import com.mstore.pojo.Account;
import com.mstore.pojo.IPAuthority;
import com.mstore.pojo.Member;
import com.mstore.pojo.SMSLog;
import com.mstore.pojo.ThirdAct;
import com.mstore.pojo.User;
import com.mstore.service.AccountService;
import com.mstore.service.IPAuthorityService;
import com.mstore.service.MemberService;
import com.mstore.service.SMSLogService;
import com.mstore.service.ThirdActService;
import com.mstore.service.UserService;
import com.mstore.service.alarm.AlarmServiceImpl;
import com.mstore.ucenter.Client;
import com.mstore.util.CookieUtils;
import com.mstore.util.RandomValidateCode;
import com.mstore.util.SendSms;
import com.mstore.util.StringUtil;

/**
 * 企业信息
 */
public class AccountAction extends BaseAction implements SessionAware,
		ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = -7895643089367643082L;

	private AccountService accountService;

	private ThirdActService thirdactService;

	private IPAuthorityService ipAuthorityService;

	private SMSLogService smsLogService;

	private MemberService memberService;

	private Account account;

	private ThirdAct thirdact;

	private String paramKey;

	private String checkCode;

	private String ysId;

	private Long actid;

	private String json;

	private String result;

	private String actName;

	private String email;

	private String mobile;

	private String password;
	private String password2;
	private String passwordOld;

	private String userMobileCode;

	private UserService userService;

	private Map<String, Object> session;

	private HttpServletRequest request;

	private HttpServletResponse response;

	private boolean check = false;

	private String message = "";

	private Member member;

	private AlarmServiceImpl alarmService;

	private String mobileCode;

	private String findPassword;

	private static Map<String, Object[]> REG_CODE_MAP = new ConcurrentHashMap<String, Object[]>();

	private static Logger logger = Logger.getLogger(AccountAction.class
			.getName());

	/**
	 * 当前页
	 */
	private int index;

	/**
	 * 总页数
	 */
	private int page;

	/**
	 * 总行数
	 */
	private int line;

	/**
	 * 商户总余额
	 */
	private float sumRbalance;

	/**
	 * 是否显示分页标签参数
	 * 0:显示; 1:不显示
	 */
	private int noPage;
	
	/**
	 * 查询内容
	 */
	private String searchText;

	private List<Account> accountsList;

	/**
	 * 企业登陆的权限标示 如果企业完善了信息，则可以正常使用功能 否则，不显示功能，只能先完善企业信息
	 */
	private String qyAuthority;

	private Integer total = 5;
	
	private String accountName;

	static {
		Timer timer = new Timer(true);
		timer.schedule(new TimerTask() {

			public void run() {
				try {
					long time = System.currentTimeMillis() / 1000;
					for (Entry<String, Object[]> entry : REG_CODE_MAP
							.entrySet()) {
						Object[] obj = entry.getValue();
						// 5分钟内有效
						if (time - ((Long) obj[0]).longValue() > 5 * 60) {
							REG_CODE_MAP.remove(entry.getKey());
						}
					}
				}
				catch (Exception e) {
				}
			}
		}, 5 * 60 * 1000, 60 * 1000);
	}

	/**
	 * 进入企业登陆页面
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String initLogin() {
		CookieUtils cookieUtils = new CookieUtils();
		account = cookieUtils.getAccountFromCookie(request);
		if (account != null) {
			mobile = account.getMobile();
		}
		return "toLoginJsp";
	}

	/**
	 * 企业登陆
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String login() {
		if (account == null || StringUtils.isBlank(account.getPassword())
				|| StringUtils.isBlank(account.getMobile())) {
			result = "手机号或密码不能为空！";
			return "error";
		}

		mobile = account.getMobile();

		Account account = accountService.findAccount(this.account);
		// 企业登陆
		if (account == null) {
			result = "手机号或密码错误！";
			return "error";
		}
		session.put("account", account);// 企业登陆

		CookieUtils cookieUtils = new CookieUtils();
		// 删除 可能已存在的cookie
		cookieUtils.delCookie(request, CookieUtils.ACCOUNT_COOKIE);
		// 将account保存到cookie中
		Cookie cookie = cookieUtils.addAccountInCookie(account);
		response.addCookie(cookie);
		logger.info(cookie.getValue() + "登陆");
		// 企业登陆
		return "success";
	}

	/**
	 * 安全退出
	 */
	public String logout() {
		session.clear();
		return "logout";
	}

	/**
	 * 验证码生成器
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public void validateCode() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		// 设置相应类型,告诉浏览器输出的内容为图片
		response.setContentType("image/jpeg");
		// 设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		RandomValidateCode randomValidateCode = new RandomValidateCode();
		try {
			// 输出图片方法
			randomValidateCode.getRandcode(request, response);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 验证码验证
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String checkCode() {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String strCode = (String) session.getAttribute("vftCode");
		if (checkCode.equalsIgnoreCase(strCode)) {
			map.put("temp", "success");
			json = mapTojson(map);
		}
		else {
			map.put("temp", "error");
			json = mapTojson(map);
		}
		return "checkCode";
	}

	/**
	 * 企业标示符唯一性验证
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String checkLogin() {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean vail = accountService.checkParamKey(paramKey);
		if (!vail) {
			map.put("temp", "success");
			json = mapTojson(map);
		}
		else {
			map.put("temp", "error");
			json = mapTojson(map);
		}
		return "checkLogin";
	}

	/**
	 * 企业账号注册
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String addAccount() {
		Client client = new Client();
		client.uc_user_register(this.account.getMobile(),
				this.account.getPassword(), this.account.getEmail());
		this.account.setCreateTime(getCreateTime());
		account.setPassword(account.getPassword());
		accountService.addAccount(this.account);
		return "add";
	}

	/**
	 * 查看企业账号信息
	 */
	public String getOneAccount() {
		String temp = "error";
		Account account = (Account) session.get("account");
		if (account != null) {
			temp = "getact";
		}
		return temp;
	}

	/**
	 * 查询微信信息
	 */
	public String getWeixin() {
		String temp = "error";
		this.account = (Account) session.get("account");
		if (this.account != null) {
			ThirdAct thirdact = new ThirdAct();
			thirdact.setEaId(this.account.getId());
			List<Object> objects = thirdactService.getAll(thirdact);
			if (objects != null) {
				this.thirdact = (ThirdAct) objects.get(0);
				temp = "getwx";
			}
			else {
				temp = "setwx";
			}
		}
		return temp;
	}

	/**
	 * 添加企业微信信息
	 */
	public String setWeixin() {
		String temp = "error";
		this.thirdact.setCreateTime(getCreateTime());
		Account account = (Account) this.session.get("account");
		if (account != null) {
			this.thirdact.setEaId(account.getId());
			this.thirdact.setAppId(this.thirdact.getAppId().trim());
			this.thirdact.setAppSecret(this.thirdact.getAppSecret().trim());
			this.thirdact.setYsId(this.thirdact.getYsId().trim());
			this.thirdactService.addThirdAccount(this.thirdact);
			temp = "addwx";
		}
		else {
			temp = "error";
		}
		return temp;
	}

	/**
	 * 修改企业微信信息
	 */
	public String editWeixin() {
		String temp = "error";
		this.account = (Account) session.get("account");
		if (this.account != null) {
			ThirdAct thirdact = new ThirdAct();
			thirdact.setEaId(this.account.getId());
			List<Object> objects = thirdactService.getAll(thirdact);
			if (objects != null) {
				this.thirdact = (ThirdAct) objects.get(0);
				temp = "editwx";
			}
			else {
				temp = "setwx";
			}
		}
		return temp;
	}

	/**
	 * 更新微信信息
	 */
	public String updateWeixin() {
		this.thirdact.setAppId(this.thirdact.getAppId().trim());
		this.thirdact.setAppSecret(this.thirdact.getAppSecret().trim());
		this.thirdact.setYsId(this.thirdact.getYsId().trim());
		this.thirdactService.updateThirdAccount(this.thirdact);
		return "updatewx";
	}

	/**
	 * 验证微信原始id唯一性
	 */
	public String verifyYsId() {
		thirdact = new ThirdAct();
		thirdact.setYsId(ysId);
		thirdact.setId(actid);
		List<Object> list = thirdactService.getThirdActByYsId(thirdact);
		if (list != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("temp", "原始id已被注册");
			json = mapTojson(map);
		}
		return "verifyReturn";
	}

	/**
	 * 验证企业名称的唯一性
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String verifyActName() {
		if (accountService.checkActName(actName)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("temp", "企业名称已被注册");
			json = mapTojson(map);
		}
		return "verifyReturn";
	}

	/**
	 * 验证企业手机号的唯一性
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String verifyActMobile() {
		if (accountService.checkActMobile(mobile)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("temp", "手机号已被注册");
			json = mapTojson(map);
		}
		return "verifyReturn";
	}

	/**
	 * 验证企业邮箱的唯一性
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String verifyActEmail() {
		if (accountService.checkActEmail(email)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("temp", "邮箱已被注册");
			json = mapTojson(map);
		}
		return "verifyReturn";
	}

	/**
	 * 验证企业标示符的唯一性
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String verifyParamKey() {
		if (accountService.checkParamKey(paramKey)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("temp", "标示符已被注册");
			json = mapTojson(map);
		}
		return "verifyReturn";
	}

	/**
	 * 修改企业密码
	 */
	public String findPassword2() {
		Map<String, Object> map = new HashMap<String, Object>();
		Member member = new Member();
		account = (Account) session.get("account");
		Account ac = accountService.findAccountById(account);
		if (ac != null) {
			String passOld = passwordOld;
			if (passOld.equals(ac.getPassword())) {
				account.setPassword(password);
				accountService.updatePassword(account);
				member.setId(ac.getMember().getId());
				member.setPassword(password);
				memberService.updataPasswordByEaId(member);
				map.put("temp", "密码修改成功");
				json = mapTojson(map);
				return "updateSuccess";
			}
			else {
				map.put("temp", "旧密码输入错误");
				json = mapTojson(map);
				return "updateSuccess";
			}

		}
		return "findPassword2Success";

	}

	/**
	 * 根据企业注册的手机号和密码来查询企业信息
	 */
	public String findAccount() {
		account = (Account) session.get("account");
		accountService.findAccount(account);
		return "findAccountSuccess";
	}

	/**
	 * 发送手机号验证码
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String sendSms() {
		Map<String, Object> map = new HashMap<String, Object>();

		if (!verifyIP()) { // 检测该IP地址申请短信的上限 true：通过，false：未通过
			map.put("temp", "未通过");
			json = mapTojson(map);
			return "sendSmsSuccess";
		}

		if (mobile == null) {
			map.put("temp", "请确认手机号已输入!");
			json = mapTojson(map);
			return "sendSmsSuccess";
		}

		SendSms sms = new SendSms();
		Map<String, Object> smsMap = sms.sendSMS(mobile.trim());
		String code = (String) smsMap.get("code");
		if (!"2".equals(code)) {
			map.put("temp", "验证码发送失败，请稍后重新获取验证码！");
			json = mapTojson(map);
			return "sendSmsSuccess";
		}
		// 保存到session
		int mobileCode = (Integer) smsMap.get("mobile_code");
		session.remove("wm" + mobile.trim());
		session.put("wm" + mobile.trim(), mobileCode);

		// 保存发送短信记录
		SMSLog smsLog = new SMSLog();
		smsLog.setCreateTime(getCreateTime());
		smsLog.setType(1); // 1代表了企业注册时发送手机号验证码
		smsLog.setMobile((String) smsMap.get("mobile"));
		smsLog.setContent((String) smsMap.get("content"));
		smsLog.setSend("2".equals(code) ? 1 : 2); // 1、发送成功；2、发送失败
		smsLogService.addSMSLog(smsLog);

		map.put("temp", "提交成功");
		json = mapTojson(map);

		return "sendSmsSuccess";
	}

	/**
	 * 验证验手机号证码
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String verifyMobileCode() {
		Map<String, Object> map = new HashMap<String, Object>();
		if (userMobileCode == null || "".equals(userMobileCode)) {
			map.put("temp", "请输入验证码！");
			json = mapTojson(map);
			return "verifyMobileCode";
		}
		if (mobile == null) {
			map.put("temp", "请确认手机号已输入!");
			json = mapTojson(map);
			return "verifyMobileCode";
		}

		Integer mobile_code = (Integer) session.get("wm" + mobile.trim());
		if (mobile_code == null) {
			map.put("temp", "请您点击【获取验证码】");
			json = mapTojson(map);
			return "verifyMobileCode";
		}
		String mobileCode = mobile_code.toString();
		if (mobileCode.equals(userMobileCode)) {
			map.put("temp", "验证码正确");
			json = mapTojson(map);
			return "sendSmsSuccess";
		}
		map.put("temp", "验证码错误");
		json = mapTojson(map);

		return "verifyMobileCode";
	}

	/**
	 * 检测IP是否到达每日访问次数限制，通过为true，未通过为false
	 */
	private boolean checkIP(String ip) {
		Date beginDate = getStartTime();
		Date endDate = getEndTime();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		IPAuthority ipAuthority = new IPAuthority();
		ipAuthority.setIp(ip);
		ipAuthority.setBeginTime(format.format(beginDate));
		ipAuthority.setEndTime(format.format(endDate));

		List<IPAuthority> ipAuthorities = ipAuthorityService
				.watchIPAuthority(ipAuthority);
		if (ipAuthorities == null || ipAuthorities.size() == 0) { // 今日首次访问
			ipAuthority.setCreateTime(format.format(new Date()));
			ipAuthority.setVisitCount(1);
			ipAuthorityService.addIPAuthority(ipAuthority);
			return true;
		}

		ipAuthority = ipAuthorities.get(0);
		if (ipAuthority.getVisitCount() >= 5) {
			modifyIPAuthorityCount(ipAuthority);
			return false;
		}

		modifyIPAuthorityCount(ipAuthority);

		return true;
	}

	/**
	 * 记录访问者访问的次数
	 */
	private void modifyIPAuthorityCount(IPAuthority ipAuthority) {
		ipAuthority.setVisitCount(ipAuthority.getVisitCount() + 1);
		ipAuthorityService.modifyIPAuthorityCount(ipAuthority);
	}

	/**
	 * 获取访问者IP
	 * 
	 * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
	 * 
	 * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
	 * 如果还不存在则调用Request .getRemoteAddr()。
	 * 
	 */
	private boolean verifyIP() {
		String ip = request.getHeader("X-Real-IP");
		if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return checkIP(ip);
		}
		ip = request.getHeader("X-Forwarded-For");
		if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				ip = ip.substring(0, index);
			}
			return checkIP(ip);
		}
		ip = request.getRemoteAddr();
		return checkIP(ip);
	}

	/**
	 * 获取当天起始时间
	 */
	private Date getStartTime() {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		return todayStart.getTime();
	}

	/**
	 * 获取当天结束时间
	 */
	private Date getEndTime() {
		Calendar todayEnd = Calendar.getInstance();
		todayEnd.set(Calendar.HOUR_OF_DAY, 23);
		todayEnd.set(Calendar.MINUTE, 59);
		todayEnd.set(Calendar.SECOND, 59);
		return todayEnd.getTime();
	}

	/**
	 * 通过session查询企业信息
	 */
	public String selectAccount() {
		Account a = (Account) session.get("account");
		account = new Account();
		account = accountService.findAccountById(a);
		return "selectAccountSuccess";
	}

	public String selectAccountToUpdate() {
		Account a = (Account) session.get("account");
		account = accountService.findAccountById(a);
		return "selectAccountToUpdateSuccess";
	}

	public String updateAccountMessage() {
		account.setName(StringUtils.isNotBlank(account.getName()) ? account
				.getName().trim() : "");
		account.setEmail(StringUtils.isNotBlank(account.getEmail()) ? account
				.getEmail().trim() : "");
		account.setMobile(StringUtils.isNotBlank(account.getMobile()) ? account
				.getMobile().trim() : "");
		account.setLoginName(StringUtils.isNotBlank(account.getLoginName()) ? account
				.getLoginName().trim() : "");
		accountService.updateAccountMessage(account);

		// 获取member_id
		String b = accountService.getByMobile(account);
		String c = b.substring(1, b.length() - 1).trim();

		Member member = new Member();
		member.setId(Long.parseLong(c));
		member = memberService.getMemberById(member);
		member.setEmail(StringUtils.isNotBlank(account.getEmail()) ? account
				.getEmail().trim() : "");
		member.setMobile(StringUtils.isNotBlank(account.getMobile()) ? account
				.getMobile().trim() : "");
		member.setName(StringUtils.isNotBlank(account.getLoginName()) ? account
				.getLoginName().trim() : "");
		memberService.updateMember(member);

		// 重新设置session
		try {
			Account a = (Account) session.get("account");
			a.setName(StringUtils.isNotBlank(account.getName()) ? account
					.getName().trim() : "");
			a.setEmail(StringUtils.isNotBlank(account.getEmail()) ? account
					.getEmail().trim() : "");
			a.setMobile(StringUtils.isNotBlank(account.getMobile()) ? account
					.getMobile().trim() : "");
			a.setLoginName(StringUtils.isNotBlank(account.getLoginName()) ? account
					.getLoginName().trim() : "");
			session.put("account", a);
		}
		catch (Exception e) {
			logger.info("session不存在", e);
			result = ERROR_TIP;
			return "error";
		}

		return "updateAccountMessage";
	}

	public String checkAll() {
		Map<String, Object> map = new HashMap<String, Object>();
		
		Account account = new Account();
		account.setId(actid);
		account = accountService.findAccountById(account);
		Long memberId = account.getMember().getId();
		
		int count = 0;
		// 验证手机号是否已被注册
		Member member = new Member();
		member.setMobile(mobile);
		member.setId(memberId);
		count = memberService.getCountFromMemberByConditionExceptSelf(member);
		if (count > 0) {
			map.put("check", true);
			map.put("message", "手机号已注册");
			json = mapTojson(map);
			return "checkAllSuccess";
		}
		
		// 验证邮箱是否已被注册
		member.clean();
		member.setEmail(email);
		member.setId(memberId);
		count = memberService.getCountFromMemberByConditionExceptSelf(member);
		if (count > 0) {
			map.put("check", true);
			map.put("message", "邮箱已注册");
			json = mapTojson(map);
			return "checkAllSuccess";
		}
		
		// 验证公司名称是否已被注册
		if (accountService.checkActName1(actName, actid)) {
			map.put("check", true);
			map.put("message", "公司名称已注册");
			json = mapTojson(map);
			return "checkAllSuccess";
		}
		
		map.put("check", false);
		json = mapTojson(map);
		return "checkAllSuccess";
	}

	/****************************************************************************************/
	/**
	 * 向手机发送验证码
	 * 
	 * @return
	 * 
	 */
	public String sendCode() {
		Map<String, Object> map = new HashMap<String, Object>();
		System.out.println(mobile);
		session.put("message", "123456");
		map.put("message", "123456");
		json = mapTojson(map);
		return "sendCode";
	}

	public String checkCode1() {
		String code = (String) session.get("message");
		if (!code.equals(checkCode)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("message", "验证码输入有误");
			json = mapTojson(map);
		}
		return "checkCode1";

	}

	/******************************************************************************************/
	/**
	 * 找回密码第一步
	 * 
	 * @return
	 */

	@Authority(actionName = "maccount", privilege = "pass")
	public String findPassword() {
		try {
			if (StringUtils.isNotBlank(findPassword)) {
				member = new Member();
				member.setMobile(findPassword);
				member.setEmail(findPassword);
				List<Member> objects = new ArrayList<Member>();
				objects = memberService.findByEmail(member);
				if (objects.size() > 0) {
					alarmService.sendMimeMessage("无觅系统：请您验证邮箱",
							"点击链接即可找回密码<a href='" + Constants.emailCallback
									+ "findpassword/resetPassword.jsp?email="
									+ findPassword + "'>"
									+ Constants.emailCallback
									+ "findpassword/resetPassword.jsp?email="
									+ findPassword + "</a>", findPassword);
					return "findPasswordByEmailSuccess";

				}
				else {

					objects = memberService.findByMobile(member);
					if (objects.size() > 0) {
						SendSms sms = new SendSms();
						Map<String, Object> smsMap = sms.sendSMS(findPassword
								.trim());
						String code = (String) smsMap.get("code");
						if (!"2".equals(code)) {
							message = "验证码发送失败，请稍后重新获取验证码！";
							return "findPasswordError";
						}
						// 保存到session
						int mobileCode = (Integer) smsMap.get("mobile_code");
						// session.remove("wm" + findPassword.trim());
						// session.put("wm" + findPassword.trim(), mobileCode);
						Object[] obj = REG_CODE_MAP.get("wm"
								+ findPassword.trim());
						long time = System.currentTimeMillis() / 1000;
						if (obj != null) {
							// 1分钟内不重复发送
							if (time - ((Long) obj[0]).longValue() <= 60) {
								message = "获取短信验证码太频繁，请稍后再试";
								return "findPasswordError";
							}
						}
						REG_CODE_MAP.put("wm" + findPassword.trim(),
								new Object[] { System.currentTimeMillis() / 1000, mobileCode });
						// 保存发送短信记录
						SMSLog smsLog = new SMSLog();
						smsLog.setCreateTime(getCreateTime());
						smsLog.setType(2); // 2代表企业修改密码
						smsLog.setMobile((String) smsMap.get("mobile"));
						smsLog.setContent((String) smsMap.get("content"));
						smsLog.setSend("2".equals(code) ? 1 : 2); // 1、发送成功；2、发送失败
						smsLogService.addSMSLog(smsLog);
						return "findPasswordByMobileSuccess";

					}
				}
				message = "邮箱或手机号码填写有误";
				return "findPasswordError";
			}
		}
		catch (Exception e) {
			logger.error("发送短信异常", e);
			result = "抱歉，没有发送成功";
			return "findPasswordError";
		}

		message = "请填写手机号码或者邮箱";
		return "findPasswordError";
	}

	/**
	 * 找回密码第三步
	 * 
	 * @return
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String updatePassword() {
		try {
			member = new Member();
			User user = new User();
			Account account = new Account();
			if (StringUtils.isNotBlank(findPassword)) {
				member.setMobile(findPassword);
				member.setEmail(findPassword);
				List<Member> objects = new ArrayList<Member>();
				objects = memberService.findByEmail(member);
				if (objects.size() > 0) {
					member.setEmail(email);
					member.setPassword(password);
					objects = memberService.findByEmail(member);

					member = objects.get(0);
					if (member.getType() == 2) {
						account.setEmail(findPassword);
						account.setPassword(password);

						accountService.updatePasswordByEmail(account);

					}
					if (member.getType() == 3) {
						user.setMember(member);
						user = userService.findUserByMemberId(user);
						user.setPassword(password);
						userService.updateUser(user);
					}

					memberService.updateMember(member);
					return "updatePasswordSuccess";
				}
				else {

					objects = memberService.findByMobile(member);
					member.setMobile(findPassword);
					member.setPassword(password);
					member = memberService.getmemberByMobile(member);

					if (member.getType() == 2) {
						account.setMobile(findPassword);
						account.setPassword(password);
						account.setMember(member);
						accountService.updatePasswordByMobile(account);
					}
					if (member.getType() == 3) {
						user.setMember(member);
						user = userService.findUserByMemberId(user);
						user.setPassword(password);
						userService.update(user);
					}
					member.setPassword(password);
					memberService.updateMember(member);
					return "updatePasswordSuccess";
				}
			}
			else {
				return "errorpage";
			}
		}
		catch (Exception e) {
			logger.info("修改密码出错", e);
			return "errorpage";
		}
	}
	
	public String FindAccountById(){
		account=accountService.FindAccountById(account, actid);
		if(account==null){
			return "accountNull";
		}
		return "FindAccountById";
	}
	
	public String UpdateAccountPassword(){
		
		String lag="修改失败";
		//将数据存储在map里，再转换成json类型数据，也可以自己手动构造json类型数据
        Map<String,Object> map = new HashMap<String,Object>();
		response.setContentType("text/html;charset=UTF-8");
		Member mem = new Member();
		account = (Account) session.get("account");
		Account acc=accountService.findAccountById(account);
		
		if(acc==null){
			return "errror";
		}
		String oldPasswod=StringUtil.MD5Encode(passwordOld);
		String password01=StringUtil.MD5Encode(password);
		String password02=StringUtil.MD5Encode(password2);
		if(!oldPasswod.equals(acc.getPassword())){
			lag="原密码错误";
		}else{
			if(password01.equals(oldPasswod)){
				lag="新密码不能与旧密码相同";
			}else{
				if(!password02.equals(password01)){
					lag="两次密码不一致";
				}
			}
			acc.setPassword(password02);
			accountService.UpdatePassword(acc);
			try {
				long memberId=acc.getMember().getId();
				mem.setId(memberId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mem.setPassword(password02);
			memberService.updataPasswordByEaId(mem);
			lag="修改成功";
			map.put("lag", lag);
			result=super.mapTojson(map);
		}
		return "UpdatePasswordSuccess";
		
	}

	/**
	 * 验证手机验证码
	 * 
	 * @return
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String checkMobileCode() {

		if (mobileCode == null || "".equals(mobileCode)) {
			message = "请输入验证码！";
			return "checkMobileCodeError";
		}

		Object[] object = REG_CODE_MAP.get("wm" + findPassword.trim());
		if (object == null) {
			message = "您输入的验证码已过期";

			return "checkMobileCodeError";
		}

		if (object[1].toString().equals(mobileCode)) {

			return "checkMobileCodeSuccess";
		}
		message = "验证码错误";

		return "checkMobileCodeError";
	}

	/**
	 * 发送手机号验证码
	 */
	@Authority(actionName = "maccount", privilege = "pass")
	public String findPasswordSendSms() {

		if (StringUtils.isBlank(findPassword)) {
			message = "请确认手机号已输入!";
			return "findPasswordSendSms";
		}
		SendSms sms = new SendSms();
		Map<String, Object> smsMap = sms.sendSMS(findPassword.trim());
		String code = (String) smsMap.get("code");
		if (!"2".equals(code)) {
			message = "验证码发送失败，请稍后重新获取验证码！";
			return "findPasswordSendSms";
		}
		// 保存到session
		int mobileCode = (Integer) smsMap.get("mobile_code");
		REG_CODE_MAP.remove("wm" + findPassword.trim());
		// session.remove("wm" + findPassword.trim());
		// session.put("wm" + findPassword.trim(), mobileCode);

		REG_CODE_MAP.put("wm" + findPassword.trim(), new Object[] {
			System.currentTimeMillis() / 1000, mobileCode });
		// 保存发送短信记录
		SMSLog smsLog = new SMSLog();
		smsLog.setCreateTime(getCreateTime());
		smsLog.setType(3); // 3 企业忘记密码
		smsLog.setMobile((String) smsMap.get("mobile"));
		smsLog.setContent((String) smsMap.get("content"));
		smsLog.setSend("2".equals(code) ? 1 : 2); // 1、发送成功；2、发送失败
		smsLogService.addSMSLog(smsLog);

		return "findPasswordSendSms";
	}

	/**
	 * 分页查询企业信息
	 */
	public String findAllAccountByPage() {
		// 商户实时余额总数
		sumRbalance = accountService.getSumRbalance();

		line = accountService.getAccountCount();

		if (line == 0) {
			line = 1;
		}
		if (line % 14 == 0) {
			page = line / 14;
		}
		else {
			page = (line / 14) + 1;
		}

		if (index < 1) {
			index = 1;
		}
		else if (index > page) {
			index = page;
		}

		accountsList = accountService.findAllAccountByPage(index);

		return "findAllAccountByPage";
	}

	/**
	 * 通过企业名称、手机号模糊查询该企业
	 */
	public String seekOneAccount() {
		// 商户实时余额总数
		sumRbalance = accountService.getSumRbalance();

		line = accountService.getAccountCount();

		accountsList = accountService.getAccoutsBySearch(searchText);
		
		noPage = 1;
		
		return "findAllAccountByPage";
	}

	/**
	 * 跳转到企业统计图页面
	 */
	public String goToAccountChart() {
		return "goToAccountChart";
	}
	
	/**
	 * 通过输入文字模糊查询企业名称
	 */
	public String searchAccountNameAuto() {
		if (StringUtils.isNotBlank(accountName)) {
			List<Account> accounts = accountService.getAccoutsBySearch(accountName);
			if (!accounts.isEmpty()) {
				List<String> accountNames = new ArrayList<String>();
				for (Account account : accounts) {
					accountNames.add(account.getName());
				}
				result = listTojson(accountNames);
			}else {
				result = "";
			}
		}else {
			result = "";
		}
		return "autocomplete";
	}
	
	public AccountService getAccountService() {
		return accountService;
	}

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public ThirdActService getThirdactService() {
		return thirdactService;
	}

	public void setThirdactService(ThirdActService thirdactService) {
		this.thirdactService = thirdactService;
	}

	public ThirdAct getThirdact() {
		return thirdact;
	}

	public void setThirdact(ThirdAct thirdact) {
		this.thirdact = thirdact;
	}

	public String getParamKey() {
		return paramKey;
	}

	public void setParamKey(String paramKey) {
		this.paramKey = paramKey;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public String getCheckCode() {
		return checkCode;
	}

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	public String getYsId() {
		return ysId;
	}

	public void setYsId(String ysId) {
		this.ysId = ysId;
	}

	public Long getActid() {
		return actid;
	}

	public void setActid(Long actid) {
		this.actid = actid;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getActName() {
		return actName;
	}

	public void setActName(String actName) {
		this.actName = actName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getUserMobileCode() {
		return userMobileCode;
	}

	public void setUserMobileCode(String userMobileCode) {
		this.userMobileCode = userMobileCode;
	}

	public IPAuthorityService getIpAuthorityService() {
		return ipAuthorityService;
	}

	public void setIpAuthorityService(IPAuthorityService ipAuthorityService) {
		this.ipAuthorityService = ipAuthorityService;
	}

	public SMSLogService getSmsLogService() {
		return smsLogService;
	}

	public void setSmsLogService(SMSLogService smsLogService) {
		this.smsLogService = smsLogService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public boolean isCheck() {
		return check;
	}

	public void setCheck(boolean check) {
		this.check = check;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	public String getQyAuthority() {
		return qyAuthority;
	}

	public void setQyAuthority(String qyAuthority) {
		this.qyAuthority = qyAuthority;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public AlarmServiceImpl getAlarmService() {
		return alarmService;
	}

	public void setAlarmService(AlarmServiceImpl alarmService) {
		this.alarmService = alarmService;
	}

	public String getMobileCode() {
		return mobileCode;
	}

	public void setMobileCode(String mobileCode) {
		this.mobileCode = mobileCode;
	}

	public String getFindPassword() {
		return findPassword;
	}

	public void setFindPassword(String findPassword) {
		this.findPassword = findPassword;
	}

	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getLine() {
		return line;
	}

	public void setLine(int line) {
		this.line = line;
	}

	public List<Account> getAccountsList() {
		return accountsList;
	}

	public void setAccountsList(List<Account> accountsList) {
		this.accountsList = accountsList;
	}

	public float getSumRbalance() {
		return sumRbalance;
	}

	public void setSumRbalance(float sumRbalance) {
		this.sumRbalance = sumRbalance;
	}

	public int getNoPage() {
		return noPage;
	}

	public void setNoPage(int noPage) {
		this.noPage = noPage;
	}

	public String getSearchText() {
		return searchText;
	}

	public void setSearchText(String searchText) {
		this.searchText = searchText;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getPasswordOld() {
		return passwordOld;
	}

	public void setPasswordOld(String passwordOld) {
		this.passwordOld = passwordOld;
	}

	public String getAccountName() {
		return accountName;
	}

	public void setAccountName(String accountName) {
		this.accountName = accountName;
	}

}
